/**
 ****************************************************************************************************
 * @file        lv_mainstart.c
 * @author      正点原子团队(ALIENTEK)
 * @version     V1.0
 * @date        2024-06-25
 * @brief       LVGL lv_keyboard(键盘) 实验
 * @license     Copyright (c) 2020-2032, 广州市星翼电子科技有限公司
 ****************************************************************************************************
 * @attention
 *
 * 实验平台:正点原子 ESP32S3 BOX 开发板
 * 在线视频:www.yuanzige.com
 * 技术论坛:www.openedv.com
 * 公司网址:www.alientek.com
 * 购买地址:openedv.taobao.com
 *
 ****************************************************************************************************
 */

#include "stdio.h"
#include "ctype.h"
#include "lv_mainstart.h"
#include "lvgl.h"
#include "hid_dev.h"
#include "esp_log.h"


/* 获取当前活动屏幕的宽高 */
#define scr_act_width()  lv_obj_get_width(lv_scr_act())
#define scr_act_height() lv_obj_get_height(lv_scr_act())
// 颜色定义
#define COLOR_BG lv_color_hex(0x0A0A0A)       // 纯黑背景
#define COLOR_KEY lv_color_hex(0x1E1E1E)      // 按键基础色
#define COLOR_ORANGE lv_color_hex(0xFF8C00)   // 橙色主色调
#define COLOR_TEXT lv_color_hex(0xE0E0E0)     // 文字颜色
#define COLOR_ACTIVE lv_color_hex(0xFFA500)   // 激活状态橙色

QueueHandle_t hid_key_queue = NULL;

// 4. 按键码转换函数示例dAqSSS
uint8_t special_mask=0;
static uint8_t convert_to_hid_keycode(const char *txt) {
    // 简化的按键映射表
    static const struct {
        const char *text;
        uint8_t hid_code;
    } key_map[] = {
        // {"A", HID_KEY_A}, 
        // {"B", HID_KEY_B}, /* 补充其他按键... */
        {"Enter", HID_KEY_ENTER},
         {" ", HID_KEY_SPACEBAR},
        {LV_SYMBOL_BACKSPACE, HID_KEY_DELETE},
        {LV_SYMBOL_NEW_LINE,  HID_KEY_ENTER},
        {LV_SYMBOL_OK,        HID_KEY_ENTER},
        {LV_SYMBOL_LEFT,      HID_KEY_LEFT_ARROW},
        {LV_SYMBOL_RIGHT,     HID_KEY_RIGHT_ARROW},    
        };
    
    for(int i = 0; i < sizeof(key_map)/sizeof(key_map[0]); i++) {
        if(strcmp(txt, key_map[i].text) == 0) {
            special_mask=0;
            return key_map[i].hid_code;
        }
    }
    if(strlen(txt) == 1) {
        char c = txt[0];
        
        // 字母处理 (A-Z a-z)
        if(isalpha(c)) {
            bool is_upper = isupper(c);
            if(is_upper) {
                special_mask =0x02 ; // 大写需要Shift修饰  不是使用 HID_KEY_LEFT_SHIFT+字符 ，而是使用掩码
            }
            else
                special_mask=0;
            return HID_KEY_A + (tolower(c) - 'a');
        }
        
        // 数字键 (0-9){{{}}}
        if(isdigit(c)) {
             special_mask=0;
            return (c == '0') ? HID_KEY_0 : (HID_KEY_1 + (c - '1'));
        }
        
        // 符号键 (需要Shift修饰的)dz-.,0...SHJH————-——@￥（）{}{}：::,,::q][
        switch(c) {
            case '!': special_mask = 0x02; return HID_KEY_1;   
            case '@': special_mask = 0x02; return HID_KEY_2;
            case '#': special_mask = 0x02; return HID_KEY_3;
            case '$': special_mask = 0x02; return HID_KEY_4;
            case '%': special_mask = 0x02; return HID_KEY_5;
            case '^': special_mask = 0x02; return HID_KEY_6;
            case '&': special_mask = 0x02; return HID_KEY_7;
            case '*': special_mask = 0x02; return HID_KEY_8;
            case '(': special_mask = 0x02; return HID_KEY_9;
            case ')': special_mask = 0x02; return HID_KEY_0;
            case '+': special_mask = 0x02; return HID_KEY_EQUAL;
            case ':': special_mask = 0x02; return HID_KEY_SEMI_COLON;
            case '_': special_mask = 0x02; return HID_KEY_MINUS;
            case '"':  special_mask = 0x02;return HID_KEY_SGL_QUOTE;
             case '?':  special_mask = 0x02;return HID_KEY_FWD_SLASH;
            case '<':  special_mask = 0x02;return HID_KEY_COMMA;
             case '>':  special_mask = 0x02;return HID_KEY_DOT;

            
            
            // 其他符号
            case '-': special_mask = 0x0; return HID_KEY_MINUS;
            case '=':  special_mask = 0x0;return HID_KEY_EQUAL;
            case '[':  special_mask = 0x0;return HID_KEY_LEFT_BRKT;
            case ']':  special_mask = 0x0;return HID_KEY_RIGHT_BRKT;
            case '\\': special_mask = 0x0;return HID_KEY_BACK_SLASH;  /*实际是字符\ */
            case ';':  special_mask = 0x0;return HID_KEY_SEMI_COLON;
            case '\'':  special_mask = 0x0;return HID_KEY_SGL_QUOTE;
            case ',':  special_mask = 0x0;return HID_KEY_COMMA;
            case '.':  special_mask = 0x0;return HID_KEY_DOT;
            case '/':  special_mask = 0x0;return HID_KEY_FWD_SLASH;
            
            
            // case '/': return HID_KEY_SLASH;
            // case '`': return HID_KEY_GRAVE;
            // case ' ': return HID_KEY_SPACE;
        }
    }
    return 0; // 未知按键
}

static lv_obj_t *kb;
static lv_obj_t *ta;
static void kb_event_cb(lv_event_t *e)
{
    /*事件确认和取消 隐藏键盘*/
    // lv_event_code_t code = lv_event_get_code(e);
    // if(code == LV_EVENT_READY || code == LV_EVENT_CANCEL) {
    //     lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
    // }
    lv_event_code_t code = lv_event_get_code(e); /* 获取事件类型 */
    lv_obj_t *target = lv_event_get_target(e);   /* 获取触发源 */
    lv_obj_t *btn = lv_event_get_current_target(e);

    // if(code == LV_EVENT_VALUE_CHANGED)
    if (code == LV_EVENT_PRESSED ||code ==LV_EVENT_LONG_PRESSED_REPEAT || code == LV_EVENT_RELEASED)
    {
        uint16_t id = lv_btnmatrix_get_selected_btn(target); /* 获取键盘按钮索引 */

        const char *txt = lv_btnmatrix_get_btn_text(target, id); /* 获取按钮文本 */
        //  ESP_LOGW("input", "%s", txt);

        if (strcmp(txt, LV_SYMBOL_KEYBOARD) == 0) /* 判断是不是键盘图标被按下 */
        {
            if (lv_keyboard_get_mode(target) == LV_KEYBOARD_MODE_NUMBER) /* 获取当前键盘模式，判断是否为数字模式 */
            {
                lv_keyboard_set_mode(target, LV_KEYBOARD_MODE_TEXT_LOWER); /* 如果是数字模式，则切换为小写字母模式 */
            }
            else
            {
                lv_keyboard_set_mode(target, LV_KEYBOARD_MODE_NUMBER); /* 不是数字模式，则切换为数字模式 */
            }
        }
        else  if(strcmp(txt, "abc") ==0 || strcmp(txt, "ABC") ==0) 
        {
            // ESP_LOGW("HID", "Queue full, drop key: %s", txt);
        }
        else
        {
            
            // 构造按键事件
            hid_key_event_t tmpevt = {
                .key_code = convert_to_hid_keycode(txt),
                .special_mask=0,  /*在之后convert_to_hid_keycode 获取的是按键更新后的mask*/
                .key_state = 0};
            if(code == LV_EVENT_RELEASED)
            {
                tmpevt.special_mask=0;
                tmpevt.key_state = 0;
            }
            else{
                tmpevt.special_mask=special_mask;
                tmpevt.key_state = 1; 
            }
                 
            // 发送到队列（非阻塞）
            if (xQueueSend(hid_key_queue, &tmpevt, 0) != pdTRUE)
            {
                ESP_LOGW("HID", "Queue full, drop key: %s", txt);
            }
        }
    }

    // if (lv_event_get_code(e) == LV_EVENT_DRAW_PART_BEGIN)
    // { // 绘制阶段触发
    //     lv_obj_draw_part_dsc_t *dsc = lv_event_get_draw_part_dsc(e);
    //     if (dsc->part == LV_PART_ITEMS)
    //     { // 处理按键绘制

    //     }
    // }
}
/* 可选：添加RGB灯效动画 */
static void rgb_effect(lv_obj_t *obj, int32_t v)
{
    lv_color_t color = lv_color_hsv_to_rgb(v % 360, 80, 90);
    lv_obj_set_style_border_color(obj, color, LV_PART_MAIN);
}

static lv_obj_t *led_indicator;
static lv_obj_t *status_label;
static lv_style_t led_style;

static lv_style_t led_shadow_style;
void init_styles() {
    // 创建柔软的阴影样式
    lv_style_init(&led_shadow_style);
    lv_style_set_shadow_color(&led_shadow_style, lv_color_hex(0x000000));
    lv_style_set_shadow_opa(&led_shadow_style, LV_OPA_50);
    lv_style_set_shadow_width(&led_shadow_style, 15);
    lv_style_set_shadow_spread(&led_shadow_style, 5);
    lv_style_set_shadow_ofs_x(&led_shadow_style, 0);
    lv_style_set_shadow_ofs_y(&led_shadow_style, 5);
}

void create_ble_indicator(lv_obj_t *parent) {
    /* 初始化样式 */
    lv_style_init(&led_style);
    lv_style_set_bg_opa(&led_style, LV_OPA_COVER);
    lv_style_set_radius(&led_style, LV_RADIUS_CIRCLE);
    lv_style_set_border_color(&led_style, lv_color_white());
    lv_style_set_border_width(&led_style, 2);

    /* 创建LED指示器 */
    led_indicator = lv_obj_create(parent);
    lv_obj_remove_style_all(led_indicator); // 清除默认样式
    lv_obj_add_style(led_indicator, &led_style, 0);
    lv_obj_add_style(led_indicator, &led_shadow_style, 0); // 添加自定义阴影
    
    lv_obj_set_size(led_indicator, 30, 30);
    lv_obj_align(led_indicator, LV_ALIGN_TOP_LEFT, 20, 20);
    lv_obj_set_style_bg_color(led_indicator, lv_color_hex(0xFF0000), 0); // 初始红色

    /* 创建状态标签 */
    status_label = lv_label_create(parent);
    // lv_label_set_text(status_label, "Disconnected");
    lv_label_set_text(status_label, "Bluetooth: HID KEYBOARD");
    lv_obj_align_to(status_label, led_indicator, LV_ALIGN_OUT_RIGHT_MID, 5, 0);
    lv_obj_set_style_text_font(status_label, &lv_font_montserrat_16, 0);
}

/* 更新状态函数 */
void update_ble_status(bool is_connected) {
    lv_obj_set_style_bg_color(led_indicator, 
        is_connected ? lv_color_hex(0x00FF00) : lv_color_hex(0xFF0000), 0);
    
    // lv_label_set_text(status_label, is_connected ? "Connected" : "Disconnected");
    
    // 添加脉冲动画
    lv_anim_t a;
    lv_anim_init(&a);
    lv_anim_set_var(&a, led_indicator);
    lv_anim_set_values(&a, 150, 255);
    lv_anim_set_time(&a, 500);
    lv_anim_set_exec_cb(&a, (lv_anim_exec_xcb_t)lv_obj_set_style_opa);
    lv_anim_start(&a);
}

void create_custom_keyboard(void) {

    create_ble_indicator(lv_scr_act());

    // 创建文本区域
    // ta = lv_textarea_create(lv_scr_act());
    // lv_obj_set_size(ta, LV_PCT(90), 80);
    // lv_obj_align(ta, LV_ALIGN_TOP_MID, 0, 20);
    
    // 创建键盘
    kb = lv_keyboard_create(lv_scr_act());
    // lv_keyboard_set_textarea(kb, ta);
    
    // 设置键盘模式为小写文本
    lv_keyboard_set_mode(kb, LV_KEYBOARD_MODE_TEXT_LOWER);
    
    /* 主键盘样式 */
    static lv_style_t style_kb;
    lv_style_init(&style_kb);
    lv_style_set_bg_color(&style_kb, COLOR_BG);
    lv_style_set_radius(&style_kb, 8);
    lv_style_set_pad_all(&style_kb, 2);
    lv_style_set_border_width(&style_kb, 2);
    lv_style_set_border_color(&style_kb, COLOR_ORANGE);
    
    // /* 按键基础样式 */
    // static lv_style_t style_kb_btn;
    // lv_style_init(&style_kb_btn);
    // lv_style_set_bg_color(&style_kb_btn, COLOR_KEY);
    // lv_style_set_radius(&style_kb_btn, 4);
    // lv_style_set_border_width(&style_kb_btn, 1);
    // lv_style_set_border_color(&style_kb_btn, lv_color_hex(0x333333));
    // lv_style_set_text_color(&style_kb_btn, COLOR_TEXT);
    // lv_style_set_text_font(&style_kb_btn, &lv_font_montserrat_16);
    
    /* 按键按下样式 */
    static lv_style_t style_kb_btn_pr;
    lv_style_init(&style_kb_btn_pr);
    lv_style_set_bg_color(&style_kb_btn_pr, COLOR_ACTIVE);
    lv_style_set_text_color(&style_kb_btn_pr, lv_color_black());
    lv_style_set_border_color(&style_kb_btn_pr, COLOR_ORANGE);
    
    // /* 特殊按键样式 (如Enter, Tab等) */
    static lv_style_t style_kb_special;
    lv_style_init(&style_kb_special);
    lv_style_set_bg_color(&style_kb_special, lv_color_darken(COLOR_KEY, 20));
    lv_style_set_text_color(&style_kb_special, COLOR_ORANGE);
    lv_style_set_border_width(&style_kb_special, 1);
    lv_style_set_border_color(&style_kb_special, COLOR_ORANGE);
    // lv_style_set_bg_color(&style_kb_special, lv_color_black());
    // lv_style_set_text_color(&style_kb_special, lv_color_hex(0xFFFFFF));

    
    // 应用主样式
    lv_obj_add_style(kb, &style_kb, 0);
    
    // 应用按键样式
    // lv_obj_add_style(kb, &style_kb_btn, LV_PART_ITEMS);
    lv_obj_add_style(kb, &style_kb_btn_pr, LV_PART_ITEMS | LV_STATE_PRESSED);
    
    // // 在LVGL 8.3.10中，特殊按键需要通过设置控制映射来标记
    // static const char *kb_map[] = {
    //     "1#", "2", "3", "4", "5", "6", "7", "8", "9", "0", "\n",
    //     "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "\n",
    //     "A", "S", "D", "F", "G", "H", "J", "K", "L", ";\n",
    //     "Z", "X", "C", "V", "B", "N", "M", ",", ".", "/", "\n",
    //     LV_SYMBOL_LEFT, " ", LV_SYMBOL_RIGHT, LV_SYMBOL_OK, ""
    // };
    
    // // 创建控制映射 - 使用LV_BTNMATRIX_CTRL_CHECKED标记特殊键
    // static lv_btnmatrix_ctrl_t ctrl_map[44];
    // for(int i = 0; i < 44; i++) {
    //     // 标记最后一行按钮为特殊键
    //     ctrl_map[i] = (i >= 40 && i <= 43) ? LV_BTNMATRIX_CTRL_CHECKED : 0;
    // }
    
    // // 设置键盘映射
    // lv_keyboard_set_map(kb, LV_KEYBOARD_MODE_TEXT_LOWER, kb_map,ctrl_map);
    
    // // 在LVGL 8.3.10中，需要通过btnmatrix的API设置控制映射
    // lv_btnmatrix_set_ctrl_map(lv_keyboard_get_btnmatrix(kb), ctrl_map);
    
    // 为特殊键应用样式
    lv_obj_add_style(kb, &style_kb_special, LV_PART_ITEMS | LV_STATE_CHECKED);
    
    // 设置键盘大小和位置
    lv_obj_set_size(kb, LV_PCT(95), LV_PCT(60));
    lv_obj_align(kb, LV_ALIGN_BOTTOM_MID, 0, -30);
    
    // 添加事件回调
    lv_obj_add_event_cb(kb, kb_event_cb, LV_EVENT_ALL, NULL);
    
    
    
    lv_anim_t a;
    lv_anim_init(&a);
    lv_anim_set_var(&a, kb);
    lv_anim_set_exec_cb(&a, (lv_anim_exec_xcb_t)rgb_effect);
    lv_anim_set_time(&a, 5000);
    lv_anim_set_values(&a, 0, 359);
    lv_anim_set_repeat_count(&a, LV_ANIM_REPEAT_INFINITE);
    lv_anim_start(&a);
}
/**
 * @brief  键盘实例
 * @param  无
 * @return 无
 */
static void lv_example_keyboard(void)
{
    create_custom_keyboard();
}

/**
 * @brief  LVGL演示
 * @param  无
 * @return 无
 */
void lv_mainstart(void)
{
    lv_example_keyboard();
}
